﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace FDSimpleModelGenerator.Json
{
    /// <summary>
    /// Json转换
    /// </summary>
    public static class JsonExtensions
    {
        /// <summary>
        /// 转json
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="camelCase">是否驼峰格式</param>
        /// <returns></returns>
        public static string ToJson(this object obj, bool camelCase = false)
        {
            if (camelCase)
            {
                return JsonConvert.SerializeObject(obj,
                    new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            }
            return JsonConvert.SerializeObject(obj);
        }

        /// <summary>
        /// Json转对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString">Json串</param>
        /// <param name="camelCase">是否驼峰格式</param>
        /// <returns></returns>
        public static T FromJson<T>(this string jsonString, bool camelCase = false)
        {
            if (camelCase)
            {
                return JsonConvert.DeserializeObject<T>(jsonString,
                    new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
            }

            if (string.IsNullOrEmpty(jsonString))
                return default;
            return JsonConvert.DeserializeObject<T>(jsonString);
        }
    }
}
